﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MetadataBasedConfigArch.Framework;
using System.Collections;
using System.Data.Objects;
using MetadataBasedConfigArch.Model;
using MetadataBasedConfigArch.Framework.Entity;

namespace MetadataBasedConfigArch.Web.Admin
{
    public partial class ManagePages : System.Web.UI.Page
    {
        #region Page Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageState = PageState.Show;
                BindData();
            }
        }

        #endregion

        #region Properties

        protected PageState PageState
        {
            get
            {
                return (PageState)(ViewState["Mode"] ?? PageState.Show);
            }
            set
            {
                ViewState["Mode"] = value;
            }
        }

        #endregion

        #region Bind Data

        protected void BindData()
        {
            //Model.Page.dd();
            using (IMetadataBasedEntityProvider entityProvider = new Model.DataEntityProvider(EntityUtil.MDAConnectionString))
            {
                var allPages = (from p in entityProvider.Load<Model.Page>() select p).LoadExtendProperties(entityProvider); 
                MainGridView.DataSource = allPages;
                MainGridView.DataBind();

            }
            PageIDHiddenInput.Value = String.Empty;
        }

        protected void BindExtendProperties(Model.Page page)
        {
            ExtendPropertyRepeater.DataSource = page.ExtendProperties;
            ExtendPropertyRepeater.DataBind();
        }

        #endregion

        #region Events

        protected void AddLinkButton_Click(object sender, EventArgs e)
        {
            if (PageState == PageState.Show)
            {
                EditPanel.Visible = true;
                ShowPanel.Visible = false;
                PageState = PageState.New;
                AddLinkButton.Text = "Go Back";
            }
            else
            {
                EditPanel.Visible = false;
                ShowPanel.Visible = true;
                AddLinkButton.Text = "Add Page";
                PageState = PageState.Show;
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (PageState == PageState.Edit)
            {
                var pageId = Convert.ToInt64(string.IsNullOrEmpty(PageIDHiddenInput.Value) ? "0" : PageIDHiddenInput.Value);
                if (pageId > 0)
                {
                    using (Model.MDAEntities entities = EntityUtil.LoadEntities())
                    {
                        var page = (from p in entities.Pages
                                    where p.ID == pageId && p.TenantID == Util.TenantID
                                    select p).FirstOrDefault();
                        if (page != null)
                        {
                            page.Name = NameTextBox.Text.Trim();
                            page.Content = ContentRadEditor.Content;
                            entities.SaveChanges();
                        }
                    }
                }
            }
            else if (PageState == PageState.New)
            {
                using (Model.MDAEntities entities = EntityUtil.LoadEntities())
                {
                    var page = new Model.Page();
                    page.Name = NameTextBox.Text.Trim();
                    page.Content = ContentRadEditor.Content;
                    entities.AddToPages(page);
                    entities.SaveChanges();
                }
            }
            BindData();
            PageIDHiddenInput.Value = String.Empty;
            EditPanel.Visible = false;
            ShowPanel.Visible = true;
            AddLinkButton.Text = "Add Page";
            PageState = PageState.Show;
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            PageIDHiddenInput.Value = String.Empty;
            EditPanel.Visible = false;
            ShowPanel.Visible = true;
            AddLinkButton.Text = "Add Page";
            PageState = PageState.Show;
        }

        #endregion

        #region GridView Events

        protected void MainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var page = e.Row.DataItem as Model.Page;

                HyperLink openDocumentLink = e.Row.Cells[1].FindControl("PageHyperLink") as HyperLink;
                openDocumentLink.NavigateUrl = "";

                Button editButton = e.Row.Cells[2].FindControl("EditButton") as Button;
                editButton.CommandArgument = page.ID.ToString();

                Button deleteButton = e.Row.Cells[2].FindControl("DeleteButton") as Button;
                editButton.CommandArgument = page.ID.ToString();
            }
        }

        protected void MainGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandArgument != null)
            {
                Int64 pageId = 0;
                Int64.TryParse(e.CommandArgument.ToString(), out pageId);
                if (pageId > 0)
                {
                    switch (e.CommandName)
                    {
                        case "EditD":
                            {
                                using (IMetadataBasedEntityProvider entityProvider = new Model.DataEntityProvider(EntityUtil.MDAConnectionString))
                                {
                                    var page = (from p in entityProvider.Load<Model.Page>()
                                                where p.ID == pageId
                                                    && p.TenantID == Util.TenantID
                                                select p).FirstOrDefault();
                                    if (page != null)
                                    {
                                        page.LoadConfigurableInfos(entityProvider);
                                        BindExtendProperties(page);

                                        NameTextBox.Text = page.Name;
                                        ContentRadEditor.Content = page.Content;
                                        PageIDHiddenInput.Value = page.ID.ToString();
                                        PageState = PageState.Edit;
                                        EditPanel.Visible = true;
                                        ShowPanel.Visible = false; 
                                        AddLinkButton.Text = "Go Back";
                                    }
                                }
                                break;
                            }
                        case "Delete":
                            {
                                using (Model.MDAEntities entities = EntityUtil.LoadEntities())
                                {
                                    var page = (from p in entities.Pages
                                                where p.ID == pageId
                                                    && p.TenantID == Util.TenantID
                                                select p).FirstOrDefault();
                                    if (page != null)
                                    {
                                        entities.DeleteObject(page);
                                        entities.SaveChanges();
                                        BindData();
                                    }
                                }
                                break;
                            }
                        default:
                            break;
                    }
                }
            }
        }

        #endregion

        protected override void OnInit(EventArgs e)
        { 
            base.OnInit(e);
            TemplateField templateField = new TemplateField();
            templateField.ShowHeader = true;
            templateField.HeaderText = "Test";
            GridViewItemTemplate itemTemplate = new GridViewItemTemplate(DataControlRowType.DataRow, "lbtn", "Name");
            itemTemplate.eh += new GridViewItemTemplate.EventHandler(itemTemplate_eh);
            templateField.ItemTemplate = itemTemplate;
            MainGridView.Columns.Add(templateField);
        }

        void itemTemplate_eh(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(GetType(), "test", "alert('ok');", true); 
            //Label1.Text = "OK";
        }

        protected void ExtendPropertyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                TextBox valueTextBox = e.Item.FindControl("Value") as TextBox;
                if (valueTextBox != null)
                {
                    valueTextBox.Text = (DataBinder.GetPropertyValue(e.Item.DataItem, "Value") ?? String.Empty).ToString();
                }
            }
        }

        protected IEnumerable<KeyValuePair<string, object>> GetRepeaterDataSource(Repeater repeater)
        {
            Dictionary<string, object> extendProperties = new Dictionary<string, object>();
            foreach (RepeaterItem item in repeater.Items)
            {
                Label keyLabel = item.FindControl("Key") as Label;
                TextBox valueTextbox = item.FindControl("Value") as TextBox;
                if (keyLabel != null && !String.IsNullOrEmpty(keyLabel.Text) && valueTextbox != null)
                {
                    extendProperties.Add(keyLabel.Text, valueTextbox.Text);
                }
            }
            return extendProperties;
        }
    }

    public class GridViewItemTemplate : ITemplate
    {
        public delegate void EventHandler(object sender, EventArgs e);
        public event EventHandler eh;

        private DataControlRowType templateType;

        private string columnName;
        private string controlID;



        public GridViewItemTemplate(DataControlRowType type, string colname)
        {

            templateType = type;

            columnName = colname;

        }
        public GridViewItemTemplate(DataControlRowType type, string controlID, string colname)
        {
            templateType = type;
            this.controlID = controlID;
            columnName = colname;
        }


        public void InstantiateIn(System.Web.UI.Control container)
        {
            switch (templateType)
            {
                case DataControlRowType.Header:
                    Literal lc = new Literal();
                    lc.Text = columnName;
                    container.Controls.Add(lc);
                    break;
                case DataControlRowType.DataRow:
                    LinkButton lbtn = new LinkButton();
                    lbtn.ID = this.controlID;
                    if (eh != null)
                    {
                        lbtn.Click += new System.EventHandler(eh);
                    }
                    lbtn.DataBinding += new System.EventHandler(lbtn_DataBinding);

                    container.Controls.Add(lbtn);

                    break;
                default:
                    break;
            }
        }
        void lbtn_DataBinding(object sender, EventArgs e)
        {
            LinkButton lbtn = sender as LinkButton;
            if (lbtn != null)
            {
                GridViewRow container = lbtn.NamingContainer as GridViewRow;
                if (container != null)
                {
                    object dataValue = DataBinder.Eval(container.DataItem, columnName);
                    if (dataValue != DBNull.Value)
                    {
                        lbtn.Text = dataValue.ToString();
                    }
                }
            }
        }
    }

}